package spring.boot.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import spring.boot.shiro.entity.User;
import spring.boot.shiro.service.UserService;


/**
 * Created by Administrator on 2018/6/10.
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/adduser")
    public String adduser(){
        return "adduser";
    }

    @RequestMapping("/unauth")
    public String unauth(){
        return "unauth";
    }

    @RequestMapping("/deluser")
    public String deluser(){
        return "deluser";
    }

    @RequestMapping("/loginUser")
    public String loginUser(String username,String passwd){
        System.out.println("===========================");
        UsernamePasswordToken token = new UsernamePasswordToken(username,passwd);
        Subject subject = SecurityUtils.getSubject();
        try {
            //调用subject.login(token)方法，走入自定义realm中的认证方法，再走入自定义credentialsMatcher进行密码效验
            subject.login(token);
            User user = (User) subject.getPrincipal();
            SecurityUtils.getSubject().getSession().setAttribute("user",user);
            return "index";
        } catch (Exception e) {
            return "login";
        }
    }

}
